<template>
  <div class="app-container" style="font-size: 14px;font-weight: 500">
    <div class="filter-container">
      <el-select ref="selectOption" v-model="value" clearable filterable placeholder="请选择国家" style="width: 300px"
                 @change="handleChange">
        <el-option
            style="width: 300px"
            v-for="item in options"
            :key="item.country_id"
            :label="item.name"
            :value="{label:item.name,value:item.country_id}">
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
        </el-option>
      </el-select>
      <el-cascader
          ref="cascader"
          :options="cascaderOptions"
          :props="props"
          clearable
          filterable
          placeholder="请选择城市"
          style="width: 500px"
          @change="handleChangeCascader">
      </el-cascader>
    </div>
    <div class="tit_btn">
      <div style="font-size: 16px;font-weight: bolder">任务明细</div>
      <div style="display: flex;position:absolute;right:20px">
        <template v-if="multipleSelection.length>0">
          <el-button size="small" @click="handleBatchDelete">删除</el-button>
          <el-button type="primary" size="small" @click="handleCreate">生成号码</el-button>
        </template>
      </div>
    </div>
    <el-table
        ref="multipleTable"
        :data="list"
        border
        fit
        size="medium"
        highlight-current-row
        @selection-change="handleSelectionChange"
        style="margin-top: 20px"
    >

      <el-table-column type="selection" align="center"/>
      <el-table-column label="序号" prop="index" width="55">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="城市代码">
        <template slot-scope="scope">
          {{ scope.row.country_name }}-{{ scope.row.city_name }}
        </template>
      </el-table-column>
      <el-table-column label="地区代码">
        <template slot-scope="scope">
          {{ scope.row.city_code }}
        </template>
      </el-table-column>
      <el-table-column label="起始号段">
        <template slot-scope="scope">
          {{ scope.row.sn_from }}
        </template>
      </el-table-column>
      <el-table-column label="结束号段">
        <template slot-scope="scope">
          {{ scope.row.sn_to }}
        </template>
      </el-table-column>
      <el-table-column label="总号数">
        <template slot-scope="scope">
          {{ scope.row.number_count }}
        </template>
      </el-table-column>
      <el-table-column label="消耗积分">
        <template slot-scope="scope">
          {{ scope.row.totalPrice }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <template>
            <el-button type="primary" size="mini" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="创建任务" :visible.sync="dialogFormVisible">
      <el-form ref="genForm" :model="genForm" :rules="genRule" label-position="left" label-width="70px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="任务名称" prop="name" label-width="150px">
          <el-input v-model="genForm.name"></el-input>
        </el-form-item>
        <el-form-item label="已选中号段数量：" label-width="200px"> {{ genForm.length }}</el-form-item>
        <el-form-item label="该任务消耗积分：" label-width="200px"> {{ genForm.totalPrice }}</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" :loading="loading" @click="onSubmit">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getGenerateCity, getGenerateCountry, genCreate} from '@/api/generate'
import splitPane from 'vue-splitpane'
import {create} from "@/api/user";

let id = 0;
export default {
  inject: ['reload'],
  components: {splitPane},
  data() {
    const _this = this // 解决el-cascader组件中 lazyLoad方法调用this指代问题
    return {
      loading: false,
      value: [],
      options: [],
      cascaderOptions: [],
      props: {
        disabled: true
      },
      list: [],
      multipleSelection: [],
      dialogFormVisible: false,
      genForm: {
        name: '',
        length: 0,
        totalPrice: 0
      },
      genRule: {
        name: [{required: true, message: this.$t('message.required')}],
      }
    }
  },
  created() {
    this.getUserCountryCodeList()
  },
  methods: {
    resize() {
      console.log('resize')
    },
    getUserCountryCodeList() {
      getGenerateCountry().then(response => {
        this.options = response.data
      })
    },
    handleChange(params) {
      this.cascaderOptions = [];
      const {label, value} = params
      if (value) {
        getGenerateCity({'country_id': value, 'country_name': label}).then(response => {
          this.cascaderOptions = response.data
        });
      }
    },
    handleChangeCascader(item) {
      const data = this.$refs['cascader'].getCheckedNodes()[0].data
      if (data) {
        const label = data.label
        const country = data.country
        const city = data.city

        const arr = label.split("-")
        data.sn_from = arr[0]
        data.sn_to = arr[1]
        data.number_count = arr[1] - arr[0]
        //国家
        const countryArr =  country.split("-")
        data.country_id = countryArr[0]
        data.country_name = countryArr[1]
        data.city_code = countryArr[2]
        //城市
        const cityArr = city.split("-")
        data.city_id = cityArr[0]
        data.city_name = cityArr[1]

        this.list.push(data)
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleBatchDelete() {
      var d = this.list;
      this.$refs.multipleTable.selection.forEach((Ele, index) => {
        //console.log(Ele.date);
        for (var i = 0; i < d.length; i++) {
          var t = d[i].value;
          if (t == Ele.value) {
            d.splice(i, 1);
          }
        }
      });
    },
    handleCreate() {
      this.dialogFormVisible = true
      this.genForm.length = this.multipleSelection.length
    },
    onSubmit() {
      this.$refs.genForm.validate(valid => {
        if (!valid) {
          return false
        }
        this.loading = true
        const params = []
        this.multipleSelection.forEach((item) => {
          const data = {}
          data.country_id = item.country_id;
          data.city_id = item.city_id;
          data.city_code = item.city_code;
          data.sn_from = item.sn_from;
          data.sn_to = item.sn_to;
          data.title = this.genForm.name;

          params.push(data)
        })
        genCreate({'params': params}).then(res => {
          this.$confirm('Create successful！', 'title', {
            confirmButtonText: 'confirm',
            showCancelButton: false,
            type: 'success'
          }).then(() => {
            this.$router.push({'name': 'genList'})
          })
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      })
    }
  }
}
</script>


<style>
.tit_btn {
  margin: 15px 20px;
  display: flex;
  align-items: center;
}
</style>
